package com.itheima.health.config;

import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class CustomerUserDetail implements UserDetailsService {
    @DubboReference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userService.findUserByName(s);
        if (user == null) {
            throw new UsernameNotFoundException("无此用户");
        }


        //拼接用户权限
        StringBuffer stringBuffer = new StringBuffer();
        for (Role role : user.getRoles()) {
            stringBuffer.append(role.getKeyword());
            stringBuffer.append(",");
            for (Permission permission : role.getPermissions()) {
                stringBuffer.append(permission.getKeyword());
                stringBuffer.append(",");
            }
        }
        if (stringBuffer.length() > 0) {
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        }


        return new org.springframework.security.core.userdetails.User(s, user.getPassword(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(stringBuffer.toString()));
    }
}
